import { FileLoader, Group } from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js';
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';

const base = window.location.origin + window.location.pathname
let gltfLoader: GLTFLoader | undefined = undefined;

async function initLoader() {
	if(gltfLoader) return gltfLoader;
	console.log('work init')
	const dracoLoader = new DRACOLoader();
	console.log(dracoLoader);
	dracoLoader.setDecoderPath( base + '/draco/gltf/' );
	dracoLoader.setWorkerLimit(4);

	const ktx2Loader = new KTX2Loader();
	ktx2Loader.setTranscoderPath( base  + '/basis/');

	const loader = new GLTFLoader();
	
	loader.setDRACOLoader(dracoLoader as any);
	loader.setKTX2Loader(ktx2Loader);
	loader.setMeshoptDecoder(MeshoptDecoder);
	gltfLoader = loader;
	return loader;
}

const LoadGLB = async function(url:string, onDone: (data: Group | undefined) => void){
	let t = await initLoader();
	console.log('work LoadGLB', url)
	t.load(url, (result) => {
		const scene = result.scene;
		scene.name = url;
		scene.userData['filename'] = url;
		scene.animations.push(...result.animations);
		onDone(scene);
		//t.dracoLoader.dispose();
	}, undefined, function ( error ) {
		console.error( error );
		onDone(undefined)
	} );
}


export { LoadGLB };
